package com.luckyframe.project.jmeter.jmeterTestPlan.context;

import com.luckyframe.project.jmeter.consumer.watch.PlanWatchTask;
import com.luckyframe.project.jmeter.execution.TestPlanStateListenter;
import com.luckyframe.project.jmeter.execution.sum.PlanResultSummariser;
import com.luckyframe.project.jmeter.jmeterTestPlan.domain.JmeterTestPlan;
import com.luckyframe.project.jmeter.jmeterTestPlanMetric.domain.JmeterTestPlanMetric;
import org.apache.jmeter.report.core.Sample;
import org.apache.jmeter.testelement.TestStateListener;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * hold the information for a jmeter test plan exuecting
 * @author lancelot
 */
public class TestPlanListener implements TestStateListener {

    private AtomicBoolean lastFinished= new AtomicBoolean(true);

    private Object lock=new Object();

    private AtomicInteger leftSize;

    private JmeterTestPlan testPlan;

    private BlockingQueue<Sample> samples=new LinkedBlockingQueue<>();

    private JmeterTestPlanMetric metric;

    private PlanWatchTask planWatchTask;


    public void addSample(Sample sample){
        this.samples.offer(sample);
    }

    public void decreaseTask(){
        if(leftSize.decrementAndGet()==0){
            testEnded();
        }
    }

    @Override
    public void testStarted() {
        if(planWatchTask==null){
            planWatchTask=new PlanWatchTask(testPlan,metric,samples);
            planWatchTask.start();
        }
    }

    @Override
    public void testStarted(String host) {

    }

    @Override
    public void testEnded() {

    }

    @Override
    public void testEnded(String host) {

    }

    public void setPlanWatchTask(PlanWatchTask planWatchTask) {
        this.planWatchTask = planWatchTask;
    }


    public void setLastFinished(AtomicBoolean lastFinished) {
        this.lastFinished = lastFinished;
    }

    public void setLock(Object lock) {
        this.lock = lock;
    }

    public JmeterTestPlan getTestPlan() {
        return testPlan;
    }

    public void setTestPlan(JmeterTestPlan testPlan) {
        this.testPlan = testPlan;
    }



    public Object getLock() {
        return lock;
    }



}
